using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Commands;

/// <summary>
/// 工单下发命令。
/// </summary>
/// <param name="WoId"></param>
public sealed record IssueWorkOrderCommand(long WoId) : IRequest<IResult<bool>>;

internal sealed class IssueWorkOrderCommandHandler(IRepository<ProdWorkOrder> repo) : IRequestHandler<IssueWorkOrderCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(IssueWorkOrderCommand request, CancellationToken cancellationToken)
    {
        var workOrder = await repo.GetByIdAsync(request.WoId, cancellationToken);
        if (workOrder == null)
        {
            return Result.Failure("未找指定的工单");
        }

        if (workOrder.Status is not WoStatusEnum.Draft and not WoStatusEnum.PendingApproval)
        {
            return Result.Failure("工单不处于草稿或审批状态，不能下发"); // 目前没有审批流程
        }

        workOrder.ChangeStatus(WoStatusEnum.Issued);
        var ok = await repo.UpdateAsync(workOrder, m => new
        {
            m.LastStatus,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
